var ordersViewData = {goodInfo : {cargos : []}};

/*
	1. 寄件人 fromAddress
	2. 收件人 toAddress
	3. 揽收地址 fetchAddress
*/


var orderFactory = {
		setFileDatas:function(fileDatas){
			this.fileDatas = fileDatas;
		},
		cookie : function(){
			var cook = document.cookie.split(";");
			var userId;
			cook.map(function(c){
				if(c.indexOf('userId') != -1){
					userId = c.split("=")[1];
				}
			});
			if(userId) return userId;
		},
		extend : function(dist, source){
			for(var i in source) if(source[i]) dist[i] = source[i];
		},

		delCargo : function(id){
			var cargos = this.state.orderCargoDtos, self = this;
			cargos.forEach(function(cargo){
				if(cargo.id === id || cargo.name === id){
					cargo.hide = true;
				}
				Select.destroy(id);
			});
			if(!this.selectIds) this.selectIds = [];
			this.selectIds.length = 0;
			this.fresh();
		},
		addressType : function(type){
			return ['fromAddress','toAddress','fetchAddress'][type-1];
		},
		handleBaseAddress : function(type,fn, res){
			var self = this;

			var query = this.state.query;

			switch(type){
				case 1: var name = 'fromAddress';break;
				case 2: var name = 'toAddress';break;
				case 3: var name = 'fetchAddress';break;
			}

			self = this;
			if(res.data && res.data.length > 0){
				self.state[name].length = 0;
				res.data.forEach(function(item){
					self.state[name].push(item);
				});

				if(!query.oid || !ordersService.source[name]){
					ordersService.source[name] = res.data[0];
				}

				self.handleAddrCheck();
				if(typeof fn == 'function') fn(res, type);
			}else{
                self.state[name] = [];
            }
			this.fresh();
		},
		handleAddrCheck : function(){
			var fromAddress = this.state.fromAddress,
				data = this.checkcustomeraddrData,
				toAddress = this.state.toAddress,
				fetchAddress = this.state.fetchAddress;
			if(fromAddress && fromAddress.length && data){
				inhance(fromAddress,data);
				this.fresh();
			}
			if(toAddress && toAddress.length && data){
				inhance(toAddress,data);
				this.fresh();
			}
			if(fetchAddress && fetchAddress.length && data){
				inhance(fetchAddress,data);
				this.fresh();
			}
			function inhance(addr,data){
				addr.forEach(function(item){
					if(data[item.id]) item.disabled = false;
					else item.disabled = true;
				});
			}

		},
		clearAddr : function(index,type) {
			var area = ['province','city','district','street'], refs = this.refs;

			area.forEach(function(item, i) {
				if(i >= index){
					$('#' + item + 'Name_' + type).val('');
					$('#' + item + 'Id_' + type).val('');

					refs[item + 'Name_' + type].resetValue('');
					refs[item + 'Id_' + type].resetValue('');

					if(i> index){
						ordersViewData[item + 'Name_' + type] && ordersViewData[item + 'Name_' + type].clearData();
					}
				}
			});
		},
		handleCountry : function(type,initData, res){    //国家下拉选择框
			var self = this, refs = self.refs, id = "countryName_" + type;
			if(res && res.data.length > 0){
				ordersViewData.countryList = res;
				this.selectFactory({
					data : [],
					id: id,
					defaultCount : 11,
					offset: -300,
					isSearch : true,
					closeLocalSearch:true,
					pagination: true,
					isSaveInputVal:true,
					defaultText: '请选择',
					searchPlaceHoder:'请输入国家名称或二字码',
					onSearchValueChange: function(attachEvent, q, currentPage){
						ordersService.searchCountry({'q':q,'pageIndex':currentPage,'pageSize':10}, function (res) {
							if(res.errorCode === 0){
								res.data.forEach(function(item, index){
									item.name += '('+item.figureCode+')';
								});
							}
							attachEvent.setData(res);
						});
					},
					attrTextModel : function(name, data, current){
						self.handleCitySelect(current, type);
						self.clearAddr(0,type);
						setValue({countryName : name, countryCode : current.code});

						if(!name){
							Select.sharePool['citysName_' + type] = null;
							ordersViewData['citysName_' + type] && ordersViewData['citysName_' + type].clearData();
							ordersViewData[id] && ordersViewData[id].clearData();
						}
					}
				});
			}
			if(initData) setValue(initData);
			function setValue(data){
				refs[id].setValue(data.countryName);
				refs['countryCode_'+type].setValue(data.countryCode);
			}
		},
		handleCitySelect : function(current, type){
			var self = this;
			if(current.code === 'CN'){
				this.handleProvince(current,type);
				this.state.isChina[type] = true;
			}else{
				this.handleForeignCity(current, type);
				this.state.isChina[type] = false;
			}
			self.fresh();
		},
		handleForeignCity : function(current, type, initData){
			var id = "citysName_" + type, refs = this.refs;
			refs[id].resetValue('');
			refs['citysId_'+type].resetValue('');
			$("#"+id).val('');
			ordersService.searchCity({countryCode : current.code,parentId:current.code},
			function(res){
				if(res.data && res.data.length > 0){
					if(ordersViewData[id]){
						ordersViewData[id].destroy();
						$("#"+id).parent("div").find(".select-container").remove();
					}
					setTimeout(function(){
						ordersViewData[id] =
						this.selectFactory({
							data : res,
							id: id,
							offset: -300,
							isSearch : true,
							closeLocalSearch : true,
							maxHeight:180,
							pagination: true,
							isSaveInputVal:true,
							defaultText: '请选择',
							searchPlaceHoder:'请输入城市名称',
							onSearchValueChange : function(attachEvent, q, currentPage){
								ordersService.searchCity({countryCode : current.code,parentId:current.code,q:q, pageSize:10, pageIndex:currentPage},
								function(res){
									if(res.errorCode === 0){
										ordersViewData[id].setData(res);
									}
								});
							},
							attrTextModel : function(name, data, current){
								setValue({cityName : name, cityId : current.id});
						}});
						if(initData) setValue(initData);
					}.bind(this),100);
				}else{
					ordersViewData[id] = null;
				}
			});

			function setValue(data){
				refs[id].setValue(data.cityName);
				refs['citysId_'+type].setValue(data.cityId);
			}
		},
		handleProvince : function(current, type, initData){    //省
			var self = this, id = "provinceName_" + type;
			ordersService.searchCity({countryCode : 'CN',parentId:current.code,'pageSize':1000,'pageIndex':1},
			function(res){
				if(res.data.length > 0){
					if(!ordersViewData[id])
						ordersViewData[id] =
						this.selectFactory({
							data : res,
							id: id,
							offset: -300,
							defaultCount: 1000,
							maxHeight: 160,
							attrTextModel : function(name, data, current){
								if(name){
									setValue({provinceName : name, provinceId : current.id});
									self.handleCity(current, type);
									self.clearAddr(1,type);
								}else{
									self.clearAddr(0,type);
								}
							}
						});
					else ordersViewData[id].setData(res);
					if(initData) setValue(initData);
				}
			});

			function setValue(data){
				if(data.provinceName)
				self.refs[id].setValue(data.provinceName);
				if(data.provinceId)
				self.refs['provinceId_'+type].setValue(data.provinceId);
			}
		},
		handleCity : function(current, type,initData){	//市
			var self = this, id = "cityName_" + type;
			ordersService.searchCity({countryCode : 'CN',parentId : current.id,'pageSize':1000,'pageIndex':1},
			function(res){
				if(res.data.length > 0){
					if(!ordersViewData[id])
						ordersViewData[id] =
						this.selectFactory({
							data : res,
							id: id,
							offset: -300,
							defaultCount: 1000,
							maxHeight: 160,
							attrTextModel : function(name, data, current){
								if(name){
									setValue({cityName:name, cityId:current.id});
									self.handleDistrict(current, type);
									self.clearAddr(2,type);
								}else{
									self.clearAddr(1,type);
								}

						}});
					else ordersViewData[id].setData(res);
					if(initData) setValue(initData);
				}
				if(!initData){  //如果不是修改的初始化页面，则打开
					ordersViewData[id].open();
				}

			});

			function setValue(data){
				if(data.cityName)
				self.refs[id].setValue(data.cityName);
				if(data.cityId)
				self.refs['cityId_'+type].setValue(data.cityId);
			}

		},
		handleDistrict : function(current, type,initData){	//区
			var self = this, id = "districtName_" + type;
			ordersService.searchCity({countryCode : 'CN',parentId : current.id,'pageSize':1000,'pageIndex':1},
			function(res){
				if(res.data.length > 0){
					if(!ordersViewData[id])
						ordersViewData[id] =
						this.selectFactory({
							data : res,
							id: id,
							offset: -300,
							defaultCount: 1000,
							maxHeight: 160,
				            direction:'up',
							attrTextModel : function(name, data, current){
								if(name){
									setValue({districtName : name, districtId:current.id});
									self.handleStreet(current, type);
									self.clearAddr(3,type);
								}else{
									self.clearAddr(2,type);
								}
							}
						});
					else ordersViewData[id].setData(res);
					if(initData) setValue(initData);
				}
				if(!initData){  //如果不是修改的初始化页面，则打开
					ordersViewData[id].open();
				}
			});

			function setValue(data){
				if(data.districtName)
				self.refs[id].setValue(data.districtName);
				if(data.districtId)
				self.refs['districtId_'+type].setValue(data.districtId);
			}

		},
		handleStreet : function(current, type,initData){	//街道
			var self = this, id = "streetName_" + type;
			ordersService.searchCity({countryCode : 'CN',parentId : current.id,'pageSize':1000,'pageIndex':1},
			function(res){
				if(res.data.length > 0){
					if(!ordersViewData[id])
						ordersViewData[id] =
						this.selectFactory({
							data : res,
							id: id,
				            direction:'up',
							offset: -300,
							defaultCount: 1000,
							maxHeight: 160,
							attrTextModel : function(name, data, current){
								setValue({streetName: name,streetId:current.id});
						}});
					else ordersViewData[id].setData(res);
					if(initData) setValue(initData);
					else setValue({});
				}
				if(!initData){  //如果不是修改的初始化页面，则打开
					ordersViewData[id].open();
				}
			});

			function setValue(data) {
				if(data.streetName)
				self.refs[id].setValue(data.streetName);
				if(data.streetId)
				self.refs['streetId_'+type].setValue(data.streetId);
			}

		},
		handleAirSea: function(type){    //海运、航运下拉框
			var self = this, refs = self.refs, id = "airSeaName_" + type;

			self.selectFactory({
				data : [],
				id: id,
				defaultText: '请选择',
				isSearch: true,
				closeLocalSearch: true,
				pagination: true,
				onSearchValueChange: function (attachEvent, data, currentPage) {
					data = data ? data : '', currentPage = currentPage ? currentPage : 1;

					var config = {
						urlParams:{
							'q':data,
							'type':self.state.productGroupRootId,
							'pageIndex':currentPage,
							'pageSize':10
						}
					};
					ordersService.getAirSeaData(config, function(res){
						var val = $('#' + id).val();

						if(res.errorCode === 0){
							res.data.forEach(function(item){
								if(item.cityName){
				                    item.name += '(' + item.contryName + '、' + item.cityName + ')';
				                }else{
				                    item.name += '(' + item.contryName + ')';
				                }
							});
							attachEvent.setData(res);
							if(val){ $('#' + id).val(val); }    //坑
						}
					});
                },
				attrTextModel : function(name, data, item){
					refs['addressDetail_'+type].setValue(item.address || '');

					refs[id].setValue(item.name);
					refs['airSeaId_'+type].setValue(item.id);
				}
			});
		},
		saveCusAddr : function(id,data){
			var self = this, pass = true, keys = [],address = {};

			if(!data['id_'+id]) delete data['id_'+id];

			for(var i in data){
				address[i.slice(0,-2)] = data[i];
				keys.push(i.slice(0,-2));
			}

			if(id == 3){    //揽收服务
				address.addressTypeCode = 11;
			}else{
				address.addressTypeCode = self.state.productGroupRootId;
			}
			if(address.addressTypeCode == 1 || address.addressTypeCode == 6){
				delete address.countryCode;
				delete address.countryName;
				delete address.provinceName;
				delete address.provinceId;
				delete address.districtName;
				delete address.districtId;
				delete address.streetId;
				delete address.streetName;
				delete address.cityName;
				delete address.cityId;
				delete address.citysName;
				delete address.citysId;
				delete address.address;
			}else{
				delete address.airSeaName;
				delete address.airSeaId;

				if(address.countryCode != 'CN'){
					delete address.provinceName;
					delete address.provinceId;
					delete address.districtName;
					delete address.districtId;
					delete address.streetId;
					delete address.streetName;
					delete address.cityName;
					delete address.cityId;
				}else{
					delete address.citysName;
					delete address.citysId;
				}
			}

			for(var i in address){
				if(i != 'addressTypeCode'){
					if(!self.refs[i+'_'+id].isValid()) pass = false;
				}
			}
			if(!pass) return;

			this.state['showAddrForm'+id] = false;
			this.fresh();

			address.type = id;
			if(address.countryCode != 'CN'){
				address.cityName = address.citysName;
				address.cityId = address.citysId;
			}

			address.transportType = address.addressTypeCode; delete address.addressTypeCode;
			if(address.transportType == this.state.seaId || address.transportType == this.state.airId){
				address.transportId = address.airSeaId;
			}

			ordersService.editAddr(address, function(res){
				if(res.errorCode == 0){
					PromptComponent.init({'type':'success','msg':res.msg}).show();
					if(!address.id) address.id = res.data;
					if(id == 3){
						ordersService.useraddressList(id, '11', self.handleBaseAddress.bind(self, id, checkCusAddr));
					}else{
						ordersService.useraddressList(id, self.state.productGroupRootId, self.handleBaseAddress.bind(self, id, checkCusAddr));
					}
				}else{
					PromptComponent.init({'type':'warning','msg':res.msg}).show();
				}
				self.refs['addr_'+id].setFormPristine();
    			self.refs['addr_'+id].reset();
			});

			function checkCusAddr(res){
				self.checkcustomeraddr(self.state.info.uid);
				var name;
				if(id == 1) name ="fromAddress";
				else if(id == 2) name = 'toAddress';
				else if(id == 3) name ='fetchAddress';
				var currentAddr;

				res.data.forEach(function(item){
					if(item.id == address.id)	currentAddr = item;
				});
				if(currentAddr)	self.selectAddress(name,currentAddr,id);
			}

		},
		upperCode : function(id, e){
			this.refs['postcode_'+id].setValue(e.target.value.toUpperCase());
		},
		searchProductInit : function(){	//搜索产品
			var self = this;
			ordersService.productList("", 1, function(res) {
				var search = self.selectFactory({
					data: res,
					id: "searchProduct",
					offset: -300,
					isSearch: true,
					isUsePinyin: true,
					pagination: true,
					closeLocalSearch: true,
					defaultText:'请选择',
					onSearchValueChange: function (attachEvent, q, currentPage) {
						ordersService.productList(q, currentPage, function (res) {
							search.setData(res);
						});
					},
					attrTextModel: function (name, data, current) {
						ordersService.productOne(current.id, self.productOne);
						// 清除货物类型下拉
						ordersService.source.orderAdditionalDtos ? ordersService.source.orderAdditionalDtos.length = 0 : "";
						self.setState({cargoTypeName: '', cargoType: '', cusWeight:''});
						self.refs.cargoTypeName.resetValue('');
						self.refs.cargoType.setValue('');

						self.refs.cusWeight.resetValue('');

						self.setState({draft_fromAddress: '',draft_toAddress:'',draft_fetchAddress:''});
						ordersService.source.fromAddress = '';
						ordersService.source.toAddress = '';
						ordersService.source.fetchAddress = {};
					}
				});
			});
		},
		initSelect : function(id){		//货物类型 select
			var self = this;
			if(!this.unitData)	ordersService.unitbase(handle.bind(this));
			else  				handle(this.unitData);

			function handle(res){
				if(!this.unitData) this.unitData = res;
				if(!this.selectIds) this.selectIds = [];
				if(!this.selectIds[id]){
					this.selectFactory({data : res,id: id,offset: -300,
						attrTextModel:function(name, data, current){
							self.refs[id].setValue(name);
							self.refs[id+'_'].setValue(current.code);
						}
					});
					this.selectIds[id] = id;
				}
			}
		},
		toggleAddrList : function(type){
			var toggle = this.state['toggleAddr'+type];
			if(toggle){
				this.state['toggleAddr'+type] = false;
			}else{
				this.state['toggleAddr'+type] = true;
			}
			this.fresh();
		},
		editAddrForm : function(type, data, trial){
			var self = this;
			if(this.state['showAddrForm'+type] && !trial) return;

			self.handleAirSea(type);

			if(!data){    //使用新地址
				init(type,{});
				setTimeout(function(){
   					self.refs['addr_' + type].setFormPristine();
   					self.refs['addr_' + type].reset();
				},50);
				if(self.state.productGroupRootId == this.state.seaId || self.state.productGroupRootId == this.state.airId){
					self.state.isOrdinary[type] = false;
				}else{
					self.state.isOrdinary[type] = true;
				}
				self.state.isOrdinary[3] = true;
   	 		}else{
				init(type,data);
				if(data.transportType == this.state.seaId || data.transportType == this.state.airId){
					this.state.isOrdinary[type] = false;
				}else{
					this.state.isOrdinary[type] = true;

					if(data.countryCode === 'CN'){
						this.state.isChina[type] = true;
						if(data.countryCode) self.handleProvince({code : data.countryCode},type,data);
						if(data.provinceId) self.handleCity({id : data.provinceId},type,data);
						if(data.cityId) self.handleDistrict({id : data.cityId},type,data);
						if(data.districtId) self.handleStreet({id : data.districtId},type,data);
					}else{
						this.state.isChina[type] = false;
						if(data.cityId) self.handleForeignCity({code : data.countryCode},type,data);
					}
				}
			}
			if(ordersViewData.countryList){
				this.handleCountry(type,data,ordersViewData.countryList);
			}else{
				ordersService.searchCountry(null, this.handleCountry.bind(this, type, data));
			}

			this.state['showAddrForm' + type] = true;
			this.fresh();
			if(!trial)
			$("html,body").animate({scrollTop: $("#addr-form-" + type).offset().top - 200},1000);

			function init(type, data){
				var refs = ['name_','phone_','postcode_','email_','address_','id_'],
					country = ['airSeaName_','airSeaId_','countryCode_','countryName_','cityName_','cityId_','districtId_','districtName_','streetId_','streetName_','citysName_','citysId_','provinceName_','provinceId_'];

				if(data.transportType == self.state.seaId || data.transportType == self.state.airId){
					self.refs['airSeaName_' + type].setValue(data.transportName);
					self.refs['airSeaId_' + type].setValue(data.transportId);

					self.refs['addressDetail_' + type].setValue(data.address);
				}

				refs.forEach(function(item){
					var val = data[item.slice(0,-1)];
					if(val) self.refs[item + type].setValue(val);
				});
				if(Object.keys(data).length === 0){
					self.state.isChina[type] = false;

					refs.forEach(function(item){
						self.refs[item+type].setValue('');
					});
					country.forEach(function(item){
						self.refs[item+type].setValue('');
					});
				}
				//self.refs['citysName_'+type].setValue(data.cityName);
			}
		},
		resetForm : function(type){
			var form = 'addr_' + type;
    		this.refs[form].reset();
    		this.state['showAddrForm' + type] = false;
    		this.fresh();
		},
		deleteAddr : function(id, type){
			var self = this;
			DialogComponent.init({'type':'confirm','msg':'确定删除此地址？', "success": function() {
                	ordersService.deleteAddr([id], function(res){

				if(res.errorCode == 0){
						var addr = this.state[this.addressType(type)],name;
						if(type === 1 && ordersService.source && ordersService.source.fromAddress){
							ordersService.source.fromAddress = {};
							name = "fromAddress";
						}else if(type === 2 && ordersService.source && ordersService.source.toAddress){
							ordersService.source.toAddress = {};
							name = "toAddress";
						}else if(type === 3 && ordersService.source && ordersService.source.fetchAddress){
							ordersService.source.fetchAddress = {};
							name = "fetchAddress";
						}
						for(var i = 0; i < addr.length; i++){
							if(addr[0].id == id){
								addr.splice(i,1);
								if(addr[0]){
									addr[0].isDefault=true;
									this.defaultAddr(addr[0].id,type);
									this.selectAddress(name,addr[0],type);
								}
								break;
							}else if(addr[i].id == id){
								addr.splice(i,1);
								break;
							}
						}
						this.fresh();
						PromptComponent.init({'type':'success','msg':res.msg}).show();
					}else{
						PromptComponent.init({'type':'warning','msg':res.msg}).show();
					}
					}.bind(self));
            }}).show();


		},
		defaultAddr : function(id, type){
			var self = this;
			if(type == 3){
				var transportType = 11;
			}else{
				var transportType = self.state.productGroupRootId;
			}

			ordersService.defaultAddr(id, type, transportType, function(res){
				if(res.errorCode == 0){
					PromptComponent.init({'type':'success','msg':res.msg}).show();
				}else{
					PromptComponent.init({'type':'warning','msg':res.msg}).show();
				}

				ordersService.useraddressList(type, transportType, self.handleBaseAddress.bind(self,type, res));
			}.bind(this));
		},
		productOne : function(res){
			var service;
			var self = this;

			this.getProGroupRootId(res.data.id, this.getAddress);

			this.hasReceived(res.data.uid, function(data){
				if(res.errorCode == 0){
					service = res.data.optionalServices ? res.data.optionalServices : [];
					ordersService.source.productUid = res.data.uid;

					//给服务数据里面添加是否是揽收服务字段
					self.serviceIsReceived(service);

					self.initService(service);
					self.setState({service : service});
					self.checkcustomeraddr(res.data.uid);
					self.initCargoTypeSelect({data : res.data.cargos});
					self.initMoreProduct(res.data);
					self.setState({info : res.data});
				}
			});
		},
		serviceIsReceived: function(service){
			var self = this;

			var serviceReceiveInfo = self.state.productReceiveData && self.state.productReceiveData.serviceReceiveInfo;

			var i = 0;
			var il = service && service.length;
			var jl = serviceReceiveInfo && serviceReceiveInfo.length;
			for(; i<il; i++){
				for(var j=0; j<jl; j++){
					if(service[i].serviceUid == serviceReceiveInfo[j].serviceUid){
						service[i].serviceReceive = serviceReceiveInfo[j].serviceReceive;
					}
				}
			}
		},
		initMoreProduct : function(data){
			var length = this.txtLength(data.introduction), MAX = 67, HEIGHT = 18;
			if(length <= MAX){
				data.more = 1;
				data.height = HEIGHT;
			}else if(length <= MAX*2){
				data.more = 2;
				data.height = HEIGHT*2;
			}else{
				data.more = 3;
				data.height = HEIGHT*2;
			}
			data.height += 'px';
			data.oldHeight = data.height;
		},
		lookMore : function(info){
			if(info.height == info.oldHeight) info.height = 'auto';
			else info.height = info.oldHeight;
			this.fresh();
		},
		checkcustomeraddr : function(uid){	//检查产品的地址服务范围
			var self = this;

			var productGroupRootId = this.state.productGroupRootId || 11;

			ordersService.checkcustomeraddr(uid, this.cookie(), productGroupRootId, function(res){
				if(res.errorCode == 0){
					self.checkcustomeraddrData = res.data;
					self.handleAddrCheck();
				}
			});
		},
		initService : function(data){
			var ids = this.state.query.serviceids,
				dtos = ordersService.source.orderAdditionalDtos,
				hasIn = false, self = this;

			if(!ids || (ids && ids.length == 0)){
				if(dtos && dtos.length){
					ids = [];
					dtos.forEach(function(dto){
						ids.push(dto.serviceUid);
					});
					ids = ids.join(",");
				}
			}

			if(!ids || (ids && ids.length == 0)){
				var feeService = ordersService.feeTrial && ordersService.feeTrial.serviceUid;
				if(feeService){
					ids = feeService;
				}
			}

			var flag = false;

			if(ids){
				ids = ids.split(",");
				data.forEach(function(ser){
					var index = ids.indexOf(ser.serviceUid);
					if(index > -1){
						ser.isChecked = true;
						if(ser.serviceReceive){
							flag = true;
						}
						self.chkService(ser, {target:{checked:true}},true);
					}else{
						ser.isChecked = false;
					}
				});
			}

			if(this.state.productReceiveData.productReceive){
				this.setState({isShowReceived : true});
			}else{
				this.setState({isShowReceived : flag});
			}
		},
		chkService : function(ser,e, isRender){
			var source = ordersService.source;

			if(!source.orderAdditionalDtos) source.orderAdditionalDtos = [];
			var dtos = source.orderAdditionalDtos,
				id = ser.serviceUid;

			if(e.target.checked){
				var isIn = false;
				dtos.forEach(function(dto){
					if(dto.serviceUid == id) isIn = true;
				});
				if(!isIn) dtos.push({serviceUid:id, serviceName:ser.serviceName});
				ser.isChecked = true;

			}else{
				var index = -1;
				dtos.forEach(function(dto, i){
					if(dto.serviceUid == id) index = i;
				});
				if(!isIn) dtos.splice(index,1);
				ser.isChecked = false;
			}

			if(!this.state.productReceiveData.productReceive){
				var data = this.state.service;
				var flag = false;
				for(var i=0, l=data.length; i<l; i++){
					if(data[i].isChecked && data[i].serviceReceive){
						flag = true; break;
					}
				}
				this.setState({isShowReceived : flag});
			}

			if(!isRender) this.fresh();
		},
		initCargoTypeSelect : function(cargos){
			var self = this;
				if(!ordersViewData.cargoTypeName){
					ordersViewData.cargoTypeName = self.selectFactory({
							data : cargos,
							id: "cargoTypeName",
							showTextField: "cargoTypeName",
							offset: -300,
							attrTextModel : function(name, data, current){
								self.refs.cargoTypeName.setValue(name);
								self.refs.cargoType.setValue(current.cargoTypeCode);
					}});
				}else
					ordersViewData.cargoTypeName.setData(cargos);
		},
		selectAddress : function(name,fd,type){
			var addrs;
			this.state['isallowChecked'+type] = true;
			ordersService.source[name] = fd;
			this.state['default_addr_'+type] = fd.id;
			this.state['isAddrShow'+type] = fd.id;
			this.fresh();
		},
		saveOrder : function(type){	//下单
			var self = this,
				oid = this.state.query.oid;

			//基础信息
			this.refs.baseForm.submit();
			if(!this.baseFormStatus) return;

			//货物明细
			var cargoIds = ordersViewData.goodInfo.cargos;
			ordersService.source.orderCargoDtos = [];

			this.state.orderCargoDtos.forEach(function(cargo){
				if(!cargo.hide)	self.refs[cargo.id].submit();
			});
			var flag = false;
			if(ordersService.source.orderCargoDtos){
				ordersService.source.orderCargoDtos.forEach(function(item){
                    for(var i in item){
                        if(i == 'goodsNumber' || i == 'goodsPrice'){
                            if(!item[i] || item[i] == '0'){
                                flag = true;return;
                            }
                        }else if(!item[i]){
                            flag = true;return;
                        }
                    }
				});
			}
			if(flag){
				PromptComponent.init({'type':'warning','msg': "物品明细不能为空!" }).show();
				return;
			}
			if(ordersService.source.orderCargoDtos.length === 0 && type != 'FEE'){
				PromptComponent.init({'type':'warning','msg': "物品明细不能为空!" }).show();
				return;
			}
			for(var i in ordersViewData.goodInfo){
				if(cargoIds.indexOf(i) != -1){
					if(!ordersViewData.goodInfo[i]){
						$('html,body').animate({scrollTop:$("#good-info").offset().top},300);
						return;
					}
				}
			}

			ordersService.source.cusUserId = this.cookie();
			ordersService.source.orderStatus = type;
			ordersService.source.customerNote = this.state.customerNotes || '';
			
			if(!ordersService.source.fromAddress.name || !ordersService.source.toAddress.name){
				PromptComponent.init({'type':'warning','msg': "收件人地址或寄件人地址不存在，请先完善地址信息!" }).show();
				return;
			}

			ordersService.source.fromName = ordersService.source.fromAddress && ordersService.source.fromAddress.name;
			ordersService.source.fromPhone = ordersService.source.fromAddress && ordersService.source.fromAddress.phone;
			ordersService.source.fromPostcode = ordersService.source.fromAddress && ordersService.source.fromAddress.postcode;
			ordersService.source.toName = ordersService.source.toAddress && ordersService.source.toAddress.name;
			ordersService.source.toPhone = ordersService.source.toAddress && ordersService.source.toAddress.phone;
			ordersService.source.toPostcode = ordersService.source.toAddress && ordersService.source.toAddress.postcode;

			if(self.state.isShowReceived){
				ordersService.source.fetchName = ordersService.source.fetchAddress && ordersService.source.fetchAddress.name;
				ordersService.source.fetchPhone = ordersService.source.fetchAddress && ordersService.source.fetchAddress.phone;
				ordersService.source.fetchPostcode = ordersService.source.fetchAddress && ordersService.source.fetchAddress.postcode;
			}else{
				ordersService.source.fetchName = '';
				ordersService.source.fetchPhone = '';
				ordersService.source.fetchPostcode = '';
				ordersService.source.fetchAddress = {};
			}

			ordersService.source.fileDtos = this.fileDatas;


			if(type === 'FEE'){	//运费预估
				this.saleProduct(ordersService.source);
				return;
			}

			if(oid){	//oid存在，表示是从草稿列表过来的，表示修改草稿
				ordersService.source.orderNo = oid;
				ordersService.modifyOrder(oid, ordersService.source,cb);
			}else{
				if(type === 'DRAFT'){
					ordersService.newOrder(ordersService.source, cb);
				}else{
					DialogComponent.init({'type':'confirm','msg':'确认提交订单？', "success": function() {
	                	ordersService.newOrder(ordersService.source, cb);
	            	}}).show();
				}

			}

			function cb(res){
				if(res.errorCode == 0){
					PromptComponent.init({'type':'success','msg':res.msg}).show();
					self.setState({orderSuccess : true, successBillNo : res.data});
					if(type === 'DRAFT') self.setState({draft : true});
					else self.setState({draft : false});
					$('html,body').animate({scrollTop:0},300);
				}else
					PromptComponent.init({'type':'warning','msg':res.msg}).show();
			}
		},
		saveGoodInfo : function(id, data){
			var valid, invalid;
			for(var i in data){
				if(data[i]) valid = true;
			}
			if(valid){
				ordersService.source.orderCargoDtos.push(data);
				ordersViewData.goodInfo.cargos.push(id);
			}
		},
		enableGoodInfo : function(id){
			ordersViewData.goodInfo[id] = true;
		},
		disableGoodInfo : function(id){
			ordersViewData.goodInfo[id] = false;
		},
		hanldeOrderService : function(res){
			if(res.errorCode == 0){
				this.orderAllStatus = res.data;
			}
		},
		baseFormFn : function(data){		//整理订单基础信息表单数据
			var keys = ['externalNo','cargoType','cargoTypeName','packageNum','cusWeight','cusWeightUnit','cusWeightUnitName'],
				self = this,
				pass = true;

			if(!this.state.showCheckExternalNo){ //为假用externalNo2
				keys[0] = 'externalNo2';
				if(this.state.showErrorNo) pass = false;
			}

			keys.forEach(function(key){
				if(!self.refs[key].isValid()) pass = false;
			});

			if(pass){
				keys.forEach(function(key){
					ordersService.source[key] = data[key];
				});

				if(ordersService.source['externalNo2']){
					ordersService.source['externalNo'] = ordersService.source['externalNo2'];
					delete ordersService.source['externalNo2'];
				}
				this.baseFormStatus = true;
				return false;
			}
			this.baseFormStatus = false;
			$('document,body').animate({scrollTop:$("#baseFormWrap").offset().top - 100},500);
			return true;
		},
		autoGenerateNo : function(e){
			var self = this;
			if(e.target.checked){
				ordersService.cusOrderNo('',cb);
				self.refs.externalNo2.setValue('');
				self.setState({showErrorNo:false})
			}else{
				self.setState({autoGenerateNumber:false});
				this.setState({showCheckExternalNo : false});
			}

			function cb(res){
				self.refs.externalNo.setValue(res.data);
				self.setState({autoGenerateNumber:true,showCheckExternalNo : true});
			}
		},
		checkExternalNo : function(e){
			var id = this.state.orderinfo_id || 0;

			var val = e.target.value, self = this;
			if(val){
				ordersService.cusOrderNoExist(val, id,cb);
			}

			function cb(res){
				if(res.errorCode == 0){
					if(res.data){
						self.setState({showErrorNo : true});
					}else{
						self.setState({showErrorNo : false});
					}
				}
			}
		},
		chkExternalNoFocus : function(){
			this.setState({showErrorNo : false});
		},
		handleUnitbase : function(res){
			var self = this;
			var ref = this.refs;

			ref.cusWeightUnitName.setValue("kg");
			ref.cusWeightUnit.setValue("kg");

			if(res.errorCode == 0){
				this.selectFactory({
						data : res,
						id: "cusWeightUnitName",
						showTextField: "code",
						offset: -300,
						attrTextModel : function(name, data, current){
							self.makeCusWeight(name, current.code);
							self.handleCheckWeight(self.state.info.uid);

				}});
				this.fresh();
			}
		},
		makeCusWeight : function(weight, unit){
			var ref = this.refs;
			ref.cusWeightUnitName.setValue(unit);
			ref.cusWeightUnit.setValue(unit);
		},
		initBaseForm : function(data){

			var keys = ['cargoType','cargoTypeName','packageNum','cusWeight','cusWeightUnit','cusWeightUnitName']; //基础表单信息
			var self = this;

			keys.forEach(function(item){
				if(data[item]){
					self.state[item] = data[item];
				}
			});

			this.makeCusWeight(data.cusWeightUnitName,data.cusWeightUnit);

			if(data.productId){
				ordersService.productOne(data.productId,this.productOne);
			}
		},
		handleCheckWeight : function(uid, event){
			var weight,unit = this.refs.cusWeightUnit.getValue();

			if(event){
				weight = parseFloat(event.target.value);
			}else{
				weight = this.refs.cusWeight.getValue();
			}

			if(isNaN(weight)) return;
			ordersService.checkweight(uid,weight,unit, function(res){
				if(res.errorCode == 0){
					this.setState({checkweightMsg : res.msg,checkweightStatus : res.data})
				}
			}.bind(this));
		},
		hasReceived: function(productUid, callback){	//产品是否有揽收服务
			var self = this;
			var config = {
				urlParams:{
					'uid': productUid
				}
			};
			ordersService.hasReceived(config, function(res){
				if(res.errorCode === 0){
					self.setState({isShowReceived : res.data.productReceive});
					self.state.productReceiveData = res.data;

					if(typeof callback == 'function'){
						callback(res.data);
					}
				}
			});
		},
		initDraft : function(res){
			var self = this;
			this.getProGroupRootId(res.data.productId, this.getAddress);

			this.initBaseForm(res.data);

			this.state.orderinfo_id = res.data.id;

			var fromAddress = res.data.fromAddress,
				toAddress = res.data.toAddress,
				fetchAddress = res.data.fetchAddress;

			if(fromAddress && fromAddress.id){
				fromAddress.name = res.data.fromName;
				fromAddress.phone = res.data.fromPhone;
				self.state.default_addr_1 = fromAddress.id;
				self.state.draft_fromAddress = fromAddress;
				ordersService.source.fromAddress = fromAddress;
			}

			if(toAddress && toAddress.id){
				toAddress.name = res.data.toName;
				toAddress.phone = res.data.toPhone;
				self.state.default_addr_2 = toAddress.id;
				self.state.draft_toAddress = toAddress;
				ordersService.source.toAddress = toAddress;
			}

			if(fetchAddress && fetchAddress.id){
				fetchAddress.name = res.data.fetchName;
				fetchAddress.phone = res.data.fetchPhone;
				self.state.default_addr_3 = fetchAddress.id;
				self.state.draft_fetchAddress = fetchAddress;
				ordersService.source.fetchAddress = fetchAddress;
			}

			var cargo = res.data.orderCargoDtos;

			if(cargo && cargo.length > 0){
				self.state.orderCargoDtos = cargo;
			}

			var dtos = res.data.orderAdditionalDtos;

			if(dtos && dtos.length){
				ordersService.source.orderAdditionalDtos = dtos;
			}

			self.state.customerNotes = res.data.customerNote;

			self.state.externalNo2 = res.data.externalNo;
			ordersService.source.customerId = res.data.customerId;
			self.fresh();

		},
		getProGroupRootId: function(productId, callback){    //根据产品Id获取产品所属根产品组
			var self = this;
			var config = {
				seatParams:{
					'productId':productId
				}
			}
			ordersService.getProGroupRootId(config, function(res){
				if(res.errorCode === 0){
					var productGroupRootId = res.data.productGroupRootId;
					if(res.data.productGroupRootId != 1 && res.data.productGroupRootId != 6){
						productGroupRootId = 11;
					}

					self.setState({'productGroupRootId':productGroupRootId});

					if(typeof callback == 'function'){
						callback(res.data.productGroupRootId);
					}
				}
			});
		},
		getAddress: function(productGroupRootId){
			var self = this;
			//发件人地址初始化
            ordersService.useraddressList(1, this.state.productGroupRootId, this.handleBaseAddress.bind(this,1, self.isRadioDis));
            //收件人地址初始化
            ordersService.useraddressList(2, this.state.productGroupRootId, this.handleBaseAddress.bind(this,2, self.isRadioDis));
            //揽收地址初始化
            ordersService.useraddressList(3, '11', this.handleBaseAddress.bind(this,3, self.isRadioDis));
		},
		isRadioDis: function(res, id){
			var self = this;
			if(!id || !res || !self.state.info.uid){ return; }

			self.checkcustomeraddr(self.state.info.uid);
			var name;
			if(id == 1) name ="fromAddress";
			else if(id == 2) name = 'toAddress';
			else if(id == 3) name ='fetchAddress';
			var currentAddr;
			var address = ordersService.source[name] || {};

            if(id == 3 && !this.state.isShowReceived){
                res.data.forEach(function(item, index){
                    if(item.isDefault){
                        address = item; return;
                    }
                });
            }

			res.data.forEach(function(item, index){
				if(item.id == address.id)	currentAddr = item;
			});
			if(currentAddr)	self.selectAddress(name,currentAddr,id);
		},
		initTrial : function(data){
			var self = this;
			data.packageNum = data.wlwh.length;

			ordersService.feeTrial = data;

			var state = this.state;
			data.productId = data.pid;
			this.initBaseForm(data);

			setTimeout(function(){
				self.editAddrForm(1, data.fromAddress,true);
				self.editAddrForm(2, data.endAddress,true);
				self.editAddrForm(3, data.fetchAddress,true);
			},1000);

			ordersService.searchCountry(null, this.handleCountry.bind(this, 1));
			ordersService.searchCountry(null, this.handleCountry.bind(this, 2));
		},
		customerNote : function(e){
			var val = e.target.value;
			if(val){
				ordersService.source.customerNote = val;
			}else{
				ordersService.source.customerNote = '';
			}
			this.setState({customerNotes : val});
		},
		saleProduct : function(data){
			var self = this;
			var sendData = {
				cargoTypeCode : data.cargoType,
				customerId : data.cusUserId,
				productUid : data.productUid,
				weightUnitCode : data.cusWeightUnit,
				packages : [{height:'',	weight: data.cusWeight}]
			};

			sendData.fromCountry = data.fromAddress.countryCode;
			sendData.fromPostcode = data.fromAddress.postcode;
			if(data.fromAddress.countryCode === 'CN'){
				sendData.fromProvince = data.fromAddress.provinceId;
				sendData.fromArea = data.fromAddress.districtId;
				sendData.fromCity = data.fromAddress.cityId;
				sendData.fromStreet = data.fromAddress.streetId;
			}else{
				sendData.fromCity = data.fromAddress.cityId;
			}
			sendData.toCountry = data.toAddress.countryCode;
			sendData.fromPostcode = data.toAddress.postcode;
			if(data.toAddress.countryCode === 'CN'){
				sendData.toProvince = data.toAddress.provinceId;
				sendData.toArea = data.toAddress.districtId;
				sendData.toCity = data.toAddress.cityId;
				sendData.toStreet = data.toAddress.streetId;
			}else{
				sendData.toCity = data.toAddress.cityId;
			}

			ordersService.saleProduct(sendData, function(res){
				if(res.errorCode == 0){
					setTotal(res.data);
				}else{
					PromptComponent.init({'type':'warning','msg':res.msg}).show();
				}
			});

			function getServiceStr(){
				var str = [];
				if(ordersService.source.orderAdditionalDtos && ordersService.source.orderAdditionalDtos.length)
				ordersService.source.orderAdditionalDtos.forEach(function(item){
					str.push(item.serviceUid);
				});
				return str.join(",");
			}


			function setTotal(data){
				var added = 0,
					serIds = getServiceStr();
				if(data[0].optionalServices && data[0].optionalServices.length && serIds){
					data[0].optionalServices.forEach(function(item){
						if(~serIds.indexOf(item.serviceUid)){
							if(typeof item.amount === 'number') added += item.amount;
						}
					});
				}
				self.setState({feeMount : data[0].totalAmount + added,feeUnit : data[0].currencyCode});
			}
		},
		txtLength : function(fData){
		    var intLength=0;
		    for (var i=0;i<fData.length;i++){
		        if ((fData.charCodeAt(i) < 0) || (fData.charCodeAt(i) > 255))
		            intLength=intLength+2;
		        else
		            intLength=intLength+1;
		    }
		    return intLength;
		},

	};

	module.exports = orderFactory;
